package com.zzs.team.Controller;

import com.google.gson.Gson;
import com.zzs.team.Service.LocationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@Controller
public class LocationController {

    @Autowired
    LocationService locationService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @ResponseBody
    @GetMapping("/location/findProcinces")
    public Map findProcinces(){

        Map map = new HashMap();
        Gson gson = new Gson();
        String provincesStr = stringRedisTemplate.opsForValue().get("provinces");

        List<String> provinces = new LinkedList<>();

        if (provincesStr==null){
            System.out.println("redis没有，从数据库拿");

            provinces = locationService.findProvinces();
            provinces.add(0,"请选择省份");

            provincesStr = gson.toJson(provinces);
            stringRedisTemplate.opsForValue().set("provinces",provincesStr);
        }else {
            System.out.println("redis里已经有了");
            provinces = gson.fromJson(provincesStr,List.class);
            System.out.println(provinces.toString());
        }


        //将所有省份放入map
        map.put("provinces",provinces);
        return map;
    }

    @GetMapping("/location/findCitiesByProvince")
    @ResponseBody
    public Map findCitiesByProvince(String provinceName){
        Map map = new HashMap();
        List<String> cities = new LinkedList<>();
        cities =  locationService.findCitiesByProvince(provinceName);
        cities.add(0,"请选择城市");

        map.put("cities",cities);
        return map;
    }

    @GetMapping("/location/findSchoolsByCity")
    @ResponseBody
    public Map findSchoolsByCity(String cityName){
        Map map = new HashMap();
        List<String> schools = new LinkedList<>();
        schools =  locationService.findSchoolsByCity(cityName);
        schools.add(0,"请选择学校");

        map.put("schools",schools);
        return map;
    }


}
